<template>
  <div>
    <BasicTable @register="registerTable" @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <template #toolbar>
        <a-button v-auth="Permission.ADD" type="primary" @click="handleCreate"> 新增 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'defaulted'">
          {{ formatDictValue(defaulted, record.defaulted) }}
        </template>
        <template v-else-if="column.key === 'action'">
          <TableAction :actions="createActions(record)" />
        </template>
      </template>
    </BasicTable>
    <DictModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup name="Dict">
import { onBeforeMount, ref } from 'vue';
import DictModal from './dict-modal.vue';
import { Permission, columns, searchFormSchema } from './dict-option';
import { delDictApi, getDictDetailListApi, getDictPageApi } from '/@/api/sys/dict';
import { useModal } from '/@/components/Modal';
import {
  BasicTable,
  ActionItem,
  EditRecordRow,
  TableAction,
  useTable,
} from '/@/components/Table';
import { useMessage } from '/@/hooks/web/useMessage';
import { formatDictValue } from '/@/utils';

const defaulted = ref([]);
onBeforeMount(async () => {
  const { data } = await getDictDetailListApi({ code: 'defaulted' });
  defaulted.value = data;
});

const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys }] = useTable({
  title: '数据字典',
  rowKey: 'dictId',
  api: getDictPageApi,
  columns,
  formConfig: {
    labelWidth: 80,
    schemas: searchFormSchema,
  },
  striped: false,
  useSearchForm: true,
  bordered: true,
  rowSelection: { type: 'radio' },
  actionColumn: {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    fixed: undefined,
  },
  afterFetch: handleAfterFetch,
});

const [registerModal, { openModal: openModal }] = useModal();

const { createMessage } = useMessage();

function handleCreate() {
  openModal(true, { isUpdate: false });
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
  });
}

function handleDelete(record: Recordable) {
  delDictApi(record.dictId).then((res) => {
    createMessage.success(res.msg);
    handleSuccess();
  });
}

function handleSuccess() {
  reload();
}

function createActions(record: EditRecordRow): ActionItem[] {
  return [
    {
      icon: 'clarity:note-edit-line',
      label: '编辑',
      auth: Permission.EDIT,
      onClick: handleEdit.bind(null, record),
    },
    {
      icon: 'ant-design:delete-outlined',
      label: '删除',
      auth: Permission.DEL,
      color: 'error',
      popConfirm: {
        title: '是否删除数据字典【' + record.title + '】？',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}

// 表格请求之后，对返回值进行处理
function handleAfterFetch(data) {
  if (data.length > 0) {
    setSelectedRowKeys([data[0].dictId]);
  } else {
    setSelectedRowKeys([]);
  }
  emitDictChange();
}

// 表格行点击事件
function handleRowClick(record: Recordable) {
  setSelectedRowKeys([record.dictId]);
  emitDictChange();
}

// 表格行选中事件
function handleSelectionChange() {
  emitDictChange();
}

// 字典变化事件
const emit = defineEmits(['dict-change']);
function emitDictChange() {
  const selectedKeys = getSelectRowKeys();
  emit('dict-change', selectedKeys.length > 0 ? selectedKeys[0] : '');
}
</script>
